import { Input, Textarea, View } from '@tarojs/components'
import { memo } from 'react'
import { formContextProvider } from '../BtForm/formContextProvider';
import Validator from '../BtForm/validator';
import './index.scss'

interface BtInputProps {
  /** 输入框类型 */
  type?: 'text' | 'number' | 'textarea'
  /** 输入框的值 */
  value?: string
  /** 占位文本 */
  placeholder?: string
  /** 是否禁用 */
  disabled?: boolean
  /** 最大长度 */
  maxLength?: number
  /** 输入框行数，type=textarea时生效 */
  rows?: number
  /** 值变化事件 */
  onChange?: (value: string) => void
  /** 自定义类名 */
  className?: string
  prop?: string
}

function BtInput({
  type = 'text',
  value = '',
  placeholder = '请填写',
  disabled = false,
  maxLength,
  onChange,
  className = '',
  prop = ''
}: BtInputProps) {
  const [state] = formContextProvider.useTracked()

  const validFormItem = async (inputValue) => {
    const rule = {}
    const field = state.fields.find(item => item.prop === prop)
    if (!field) return
    if (state.rules[prop]) {
      rule[prop] = state.rules[prop]
    }
    const validator = new Validator(rule)
    const errs = await validator.validate({ [prop]: inputValue })
    const msg = (errs && errs[0].message) || ''
    field.setErrMsg(msg)
  }
  const handleInput = (e: any) => {
    const inputValue = e.detail.value
    if (prop) {
      validFormItem(inputValue)
    }
    onChange?.(inputValue)
  }

  const renderCounter = () => {
    if (!maxLength) return null
    return (
      <View className='bt-input__counter'>
        {value.length}/{maxLength}
      </View>
    )
  }

  if (type === 'textarea') {
    return (
      <View className='bt-input-wrapper'>
        <Textarea
          className={`bt-input bt-input--textarea ${className}`}
          value={value}
          placeholder={placeholder}
          placeholderClass='bt-input__placeholder'
          disabled={disabled}
          maxlength={maxLength}
          autoHeight
          onInput={handleInput}
        />
        {renderCounter()}
      </View>
    )
  }

  return (
    <View className='bt-input-wrapper flex'>
      <Input
        className={`bt-input flex-1 ${className}`}
        type={type}
        value={value}
        placeholder={placeholder}
        placeholderClass='bt-input__placeholder'
        disabled={disabled}
        maxlength={maxLength}
        onInput={handleInput}
      />
      {renderCounter()}
    </View>
  )
}

export default memo(BtInput)
